<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CustomerInfoResource;
use App\Http\Requests\Api\CustomerInfoRequest;
use App\Models\CustomerInfo;
use App\Models\UserDraw;
use App\Models\Vehicle;
use Illuminate\Http\Request;
use App\Http\Queries\CustomerInfoQuery;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use App\Http\Requests\Api\DriverRequest;
use App\Models\Dealer;
use App\Http\Requests\Api\LngLatRequest;

class CustomerInfoController extends Controller
{
    public function store(CustomerInfoRequest $request, CustomerInfo $customerInfo, UserDraw $userDraw)
    {
        $user = $request->user();
        $vehicle = Vehicle::find($request->vehicle_id);
        if (!$vehicle) {
            return $this->failed('vehicle-not-found');
        }

        //修改用户信息
        !empty($user->name) ?: $user->name = $request->name;
        !empty($user->province) ?: $user->province = $request->province;
        !empty($user->city) ?: $user->city = $request->city;
        $user->save();

        $customerInfo->fill($request->all());
        $customerInfo->user_id = $user->id;
        $customerInfo->channel = $user->channel;
        $customerInfo->activity_id = $vehicle->activity_id;

        if ($vehicle->series->recommend && $request->referee_id) {
            $customerInfo->referee_id = $request->referee_id;
        }
        $customerInfo->save();
        $customerInfo->is_get_chance = false;
        if ($vehicle->activity_id && app()->environment('local')) {
            goto loop;
        }
        if ($vehicle->activity_id && $userDraw->where('activity_id', $vehicle->activity_id)->where('user_id', $user->id)->doesntExist()) {
            loop:
            $userDraw->addRecond($vehicle->activity_id, $user->id, $customerInfo->id);
            $customerInfo->is_get_chance = true;
        }
        return $this->resource(new CustomerInfoResource($customerInfo));
    }

    public function index(Request $request, CustomerInfoQuery $query)
    {
        $user = $request->user();
        $rows = $query->where('user_id', $user->id)->paginate(10);
        return $this->resource(CustomerInfoResource::collection($rows));
    }

    public function update(CustomerInfoRequest $request, CustomerInfo $customerInfo)
    {
        $this->authorize('own', $customerInfo);
        $customerInfo->fill($request->only('province', 'city', 'dealer_id'));
        $customerInfo->save();
        return $this->resource(new CustomerInfoResource($customerInfo));
    }

    public function show($id, CustomerInfoQuery $query)
    {
        $customerInfo = $query->findOrFail($id);
        $this->authorize('own', $customerInfo);
        return $this->resource(new CustomerInfoResource($customerInfo));
    }

    public function driver(CustomerInfo $customerInfo, LngLatRequest $request)
    {
        $this->authorize('own', $customerInfo);
        if ($customerInfo->driver_at) {
            return $this->failed('have-driver');
        }

        $location = $request->lat . ',' . $request->lng;
        $to = $customerInfo->dealer->lat . ',' . $customerInfo->dealer->lng;
        $result = app('App\Services\MapService')->distance($location, $to);
        $distance = $result['rows'][0]['elements'][0]['distance'];
        if ($distance > 1000) {
            //您未在门店附近，请前往门店试驾,请确认您是否已开启小程序定位
            $gl = $distance / 1000;
            return $this->failed('out-of-range', '您距离门店还有' . round($gl, 1) . '公里，超出试驾范围');
        }
        $key = 'dfjk-driver-' . $customerInfo->id . '-' . Str::random(5);
        $expiredAt = Carbon::now()->addMinutes(4320);
        Cache::put($key, $customerInfo->id, $expiredAt);
        $qrcode = app('qrcode')->format('png')
            ->size(150)
            ->margin(0)
            ->errorCorrection('H')
            ->generate($key);

        $data = [
            'qrcode_key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
            'qrcode' => base64_encode($qrcode)
        ];
        return $this->success($data);
    }

    public function getClueByKey(Request $request, CustomerInfo $customerInfo)
    {
        $cache = Cache::get($request->key);
        if (!$cache) {
            return $this->failed('model-not-found-exception', '无效的key');
        }
        $row = $customerInfo->where('id', $cache)->with(['vehicle', 'dealer'])->firstOrFail();
        return $this->resource(new CustomerInfoResource($row));
    }

    public function driverVerify(DriverRequest $request)
    {
        $clue = CustomerInfo::where('id', $request->id)->firstOrFail();
        if ($clue->dealer->code != $request->dealer_code) {
            return $this->failed('driver-mismatching');
        }
        if ($clue->driver_at) {
            return $this->failed('have-driver');
        }
        $clue->driver_at = Carbon::now();
        $clue->save();
        return $this->resource(new CustomerInfoResource($clue));
    }

    public function count(Request $request, CustomerInfoQuery $query)
    {
        $user = $request->user();
        $count = $query->where('user_id', $user->id)->count();
        $data = [
            'count' => $count
        ];
        return $this->success($data);
    }

    //经销商试驾记录
    public function drives(DriverRequest $request, CustomerInfoQuery $query)
    {
        $dealer = Dealer::where('code', $request->dealer_code)->first();
        $dealer_id = is_null($dealer) ? 0 : $dealer->id;
        $rows = $query->where('dealer_id', $dealer_id)->whereNotNull('driver_at')->paginate(10);
        return $this->resource(CustomerInfoResource::collection($rows));
    }

    public function list(CustomerInfoQuery $query)
    {
        $rows = $query->paginate(10);
        return $this->resource(CustomerInfoResource::collection($rows));
    }

    public function default($id, CustomerInfoQuery $query)
    {
        $customerInfo = $query->findOrFail($id);
        return $this->resource(new CustomerInfoResource($customerInfo));
    }

    public function all(CustomerInfoQuery $query)
    {
        $rows = $query->get();
        return $this->resource(CustomerInfoResource::collection($rows));
    }
}
